package com.hzsai.nettylearn.server;

import com.hzsai.nettylearn.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * hzsai 2019/11/14
 * usage: socketserver连接测试客户端
 **/
@Component
public class TimeClient {

    private static final Logger logger = LoggerFactory.getLogger(TimeClient.class);

    @Value("${timeserver.port}")
    private int serverPort;

    @Value("${timeserver.ip}")
    private String ip;

    private Socket socket = null;

    public TimeClient() {
    }

    public void start() throws IOException, InterruptedException {
        boolean connectable = false;
        while (!connectable) {
            //Thread.currentThread().sleep(10000);
            logger.info(DateTimeUtil.getDate() + "Client: Connecting to server 【{}】...", ip + ":" +  String.valueOf(serverPort));
            socket = new Socket(ip, serverPort);
            connectable = true;
        }
        logger.info(DateTimeUtil.getDate() + "Client: connected.");
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter   out = new PrintWriter(socket.getOutputStream());

        out.println(" Hello server, I'm client! ");
        out.println(" Hello server, I'm client! ");
        out.println(" Hello server, I'm client! ");
        out.flush();
        out.close();
        in.close();
        socket.close();
    }

    public void stop() throws IOException {
        if (socket != null)
            socket.close();
        socket = null;
    }

    public void sendMsg(String msg) throws IOException, InterruptedException {
        if (socket == null)
            start();
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        logger.info(DateTimeUtil.getDate() + "Client: sending msg: " + msg);
        out.println(DateTimeUtil.getDate() + "Client: " + msg);
        out.close();
    }
}
